package com.ls.controller;


import com.ls.model.Department;
import com.ls.service.DeptRemoteClient;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("portal")
public class PortalController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DeptRemoteClient deptRemoteClient;
    @GetMapping("/depts")
    public List<Department> portals() {
        ResponseEntity<List> entity = restTemplate.getForEntity("http://localhost:9090/service/depts", List.class);
        System.out.println("portal被访问了");
        return entity.getBody();
    }

    //@LoadBalanced //使用Ribbon实现负载均衡的调用(注册中心调用)
    // 在restTemplate上加
    @GetMapping("/depts2")
    public List<Department> portals2() {
        ResponseEntity<List> entity = restTemplate.getForEntity("http://001-SPRINGCLOUD-SERVICE-GOODS/service/depts", List.class);
        System.out.println("portal2被访问了");
        return entity.getBody();
    }


    @GetMapping("/deptsFeign")
    public List<Department> portalsFeign() {
        return deptRemoteClient.depts();
    }

    //测试断路器
    @HystrixCommand(fallbackMethod = "fallback")
    @GetMapping("/deptHystrix")
    public List<Department> portalsHystrix() {
        return deptRemoteClient.depts();
    }

    public List<Department> fallback(){
        System.out.println("断路器执行了");
        List<Department> list = new ArrayList<>();
        Department department = new Department(10, "出错的数据", new Date());
        list.add(department);
        return list;
    }
}
